<template>
  <div class="energy-storage-planning-box">
    <!-- 返回按钮 -->
    <div class="form-header">
      <el-button icon="el-icon-arrow-left" @click="handleGoBack"
        >返回</el-button
      >
    </div>
    <!-- 步骤导航 -->
    <div class="step-navigation">
      <el-steps :active="currentStep" finish-status="success" simple>
        <el-step
          v-for="(step, index) in steps"
          :key="index"
          :title="step.title"
        ></el-step>
      </el-steps>
    </div>

    <!-- 步骤内容 -->
    <div class="step-content">
      <!-- 第1步 -->
      <StepOne
        v-if="currentStep === 0"
        ref="stepOne"
        :form-data="formData"
        :manage-no="manageNo"
        :readonly="isViewMode"
        @update:form-data="handleFormDataUpdate"
      />
      <!-- 第2步 -->
      <StepTwo
        v-else-if="currentStep === 1"
        ref="stepTwo"
        :form-data="formData"
        :step-one-id="formData.stepOneId"
        :readonly="isViewMode"
        @update:form-data="handleFormDataUpdate"
      />
      <!-- 第3步 -->
      <StepThree
        v-else-if="currentStep === 2"
        ref="stepThree"
        :form-data="formData"
        :step-one-id="formData.stepOneId"
        :readonly="isViewMode"
        @update:form-data="handleFormDataUpdate"
      />
      <!-- 第4步 -->
      <StepFour
        v-else-if="currentStep === 3"
        ref="stepFour"
        :form-data="formData"
        :step-one-id="formData.stepOneId"
        :readonly="isViewMode"
        @update:form-data="handleFormDataUpdate"
      />
      <!-- 查看规划结果 -->
      <ViewResult
        v-else-if="currentStep === 4"
        :form-data="formData"
        :result-data="formData.resultData"
      />
    </div>

    <!-- 底部操作按钮 -->
    <div class="footer-actions">
      <!-- 查看模式：只显示上一步和下一步按钮 -->
      <template v-if="isViewMode">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button
          v-if="currentStep < steps.length - 1"
          type="primary"
          @click="nextStep"
          >下一步</el-button
        >
      </template>
      <!-- 编辑模式：显示正常的操作按钮 -->
      <template v-else>
        <el-button v-if="currentStep > 0 && currentStep !== 4" @click="prevStep">上一步</el-button>
        <el-button
          v-if="currentStep < steps.length - 1 && currentStep !== 3"
          type="primary"
          @click="nextStep"
          >下一步</el-button
        >
        <!-- 第四步显示提交按钮 -->
        <el-button
          v-if="currentStep === 3"
          type="primary"
          @click="nextStep"
          >提交</el-button
        >
        <!-- 查看规划结果步骤显示上一步和完成按钮 -->
        <template v-if="currentStep === 4">
          <el-button @click="prevStep">上一步</el-button>
          <el-button
            type="success"
            @click="handleComplete"
            >完成</el-button
          >
        </template>
      </template>
    </div>
  </div>
</template>

<script>
import StepOne from './components/StepOne.vue'
import StepTwo from './components/StepTwo.vue'
import StepThree from './components/StepThree.vue'
import StepFour from './components/StepFour.vue'
import ViewResult from './components/ViewResult.vue'
import {
  getServiceProviderApi,
  stepOneAddOrUpdateApi,
  stepTwoAddOrUpdateApi,
  stepThreeAddOrUpdateApi,
  stepFourAddOrUpdateApi,
  stepFiveAddOrUpdateApi,
  getEnergyStoragePlanByIdApi
} from '@/api/Microgrid/EnergyStoragePlanning'

export default {
  name: 'EnergyStoragePlanningForm',
  components: {
    StepOne,
    StepTwo,
    StepThree,
    StepFour,
    ViewResult
  },
  props: {
    initialData: {
      type: Object,
      default: null
    },
    initialMode: {
      type: String,
      default: 'edit'
    }
  },
  data() {
    return {
      manageNo: '', // 服务商编码
      currentStep: 0,
      mode: 'edit', // 'edit' 或 'view'
      isViewMode: false, // 是否为查看模式
      steps: [
        { title: '第1步' },
        { title: '第2步' },
        { title: '第3步' },
        { title: '第4步' },
        { title: '查看规划结果' }
      ],
      formData: {
        // 第1步数据
        region: '', // 地区
        projectName: '', // 项目名称&描述
        priceSchemeId: '', // 电价方案ID
        month: '', // 月份
        priceConfig: {
          // 电价配置
          peak: {
            price: '0.00',
            timePeriods: []
          },
          high: {
            price: '0.00',
            timePeriods: []
          },
          flat: {
            price: '0.00',
            timePeriods: []
          },
          offPeak: {
            price: '0.00',
            timePeriods: []
          },
          superOffPeak: {
            price: '0.00',
            timePeriods: []
          }
        },
        // 后续步骤的数据
        stepTwoData: {},
        stepThreeData: {},
        stepFourData: {},
        // 保存第一步后返回的ID（用于修改）
        stepOneId: null,
        // 第四步返回的规划结果数据
        resultData: null
      }
    }
  },
  async mounted() {
    // 获取服务商编码
    await this.getManageNo()
    // 如果有初始数据，直接加载
    if (this.initialData) {
      await this.$nextTick()
      this.loadDataFromInitial(this.initialData, this.initialMode)
    }
    // 确保 manageNo 设置后再渲染子组件
    this.$nextTick(() => {
      // manageNo 已经通过 props 传递给 StepOne，watch 会自动触发
    })
  },
  watch: {
    initialData: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.loadDataFromInitial(newVal, this.initialMode)
          })
        }
      },
      immediate: false
    }
  },
  methods: {
    // 获取服务商编码
    async getManageNo() {
      try {
        const res = await getServiceProviderApi()
        if (res.code === 200 && res.data && res.data.entity) {
          this.manageNo = res.data.entity.manageNo
        }
      } catch (error) {
        console.error('获取服务商信息失败:', error)
      }
    },
    // 跳转到指定步骤
    goToStep(index) {
      // 可以添加验证逻辑，只有完成前面的步骤才能跳转
      this.currentStep = index
    },
    // 上一步
    prevStep() {
      if (this.currentStep > 0) {
        this.currentStep--
      }
    },
    // 下一步
    async nextStep() {
      // 如果是查看模式，只切换步骤，不调用保存接口
      if (this.isViewMode) {
        if (this.currentStep < this.steps.length - 1) {
          this.currentStep++
        }
        return
      }

      // 第一步：验证基本信息并保存
      if (this.currentStep === 0) {
        if (this.$refs.stepOne) {
          const isValid = this.$refs.stepOne.validateForm()
          if (!isValid) {
            // 验证失败，不进入下一步
            return
          }
          // 验证通过，保存第一步数据
          try {
            const submitData = this.$refs.stepOne.getSubmitData()
            // 如果是修改，需要传递 id
            if (this.formData.stepOneId) {
              submitData.id = this.formData.stepOneId
            }
            const res = await stepOneAddOrUpdateApi(submitData)
            if (res && res.code === 200) {
              // 保存成功，保存返回的ID（如果有）
              if (res.data && res.data.entity) {
                this.formData.stepOneId = res.data.entity
              }
              
              // 重新保存第一步后，重置后续步骤的数据
              this.formData.stepTwoData = {}
              this.formData.stepThreeData = {}
              this.formData.stepFourData = {}
              
              // 如果后续步骤组件已渲染，重置它们的数据
              this.$nextTick(() => {
                if (this.$refs.stepTwo) {
                  this.$refs.stepTwo.resetStepTwoData()
                }
                if (this.$refs.stepThree) {
                  this.$refs.stepThree.resetStepThreeData()
                }
                if (this.$refs.stepFour) {
                  this.$refs.stepFour.resetStepFourData()
                }
              })
              
              this.$message.success('保存成功')
              // 进入下一步
              if (this.currentStep < this.steps.length - 1) {
                this.currentStep++
              }
            } else {
              this.$message.error(res.message || '保存失败')
            }
          } catch (error) {
            console.error('保存第一步数据失败:', error)
            this.$message.error('保存失败，请重试')
          }
        }
      } else if (this.currentStep === 1) {
        // 第二步：保存第二步数据
        if (this.$refs.stepTwo) {
          try {
            const submitData = this.$refs.stepTwo.getSubmitData()
            // 必须要有第一步的ID
            if (!submitData.id) {
              this.$message.warning('请先完成第一步')
              return
            }
            // 必须要有导入的负荷数据
            if (!submitData.loadDetailsList || submitData.loadDetailsList.length === 0) {
              this.$message.warning('请先导入负荷数据')
              return
            }
            const res = await stepTwoAddOrUpdateApi(submitData)
            if (res && res.code === 200) {
              this.$message.success('保存成功')
              // 进入下一步
              if (this.currentStep < this.steps.length - 1) {
                this.currentStep++
              }
            } else {
              this.$message.error(res.message || '保存失败')
            }
          } catch (error) {
            console.error('保存第二步数据失败:', error)
            this.$message.error('保存失败，请重试')
          }
        } else {
          // 如果没有 ref，直接进入下一步
          if (this.currentStep < this.steps.length - 1) {
            this.currentStep++
          }
        }
      } else if (this.currentStep === 2) {
        // 第三步：保存第三步数据
        if (this.$refs.stepThree) {
          try {
            const submitData = this.$refs.stepThree.getSubmitData()
            // 必须要有第一步的ID
            if (!submitData.id) {
              this.$message.warning('请先完成第一步')
              return
            }
            // 验证变压器容量
            if (!submitData.transformerCapacity || submitData.transformerCapacity <= 0) {
              this.$message.warning('请输入变压器容量')
              return
            }
            const res = await stepThreeAddOrUpdateApi(submitData)
            if (res && res.code === 200) {
              this.$message.success('保存成功')
              // 进入下一步
              if (this.currentStep < this.steps.length - 1) {
                this.currentStep++
              }
            } else {
              this.$message.error(res.message || '保存失败')
            }
          } catch (error) {
            console.error('保存第三步数据失败:', error)
            this.$message.error('保存失败，请重试')
          }
        } else {
          // 如果没有 ref，直接进入下一步
          if (this.currentStep < this.steps.length - 1) {
            this.currentStep++
          }
        }
      } else if (this.currentStep === 3) {
        // 第四步：保存第四步数据
        if (this.$refs.stepFour) {
          try {
            const submitData = this.$refs.stepFour.getSubmitData()
            // 必须要有第一步的ID
            if (!submitData.id) {
              this.$message.warning('请先完成第一步')
              return
            }
            const res = await stepFourAddOrUpdateApi(submitData)
            if (res && res.code === 200) {
              // 保存返回的数据到 formData.resultData
              // 根据接口文档，返回数据在 res.data.entity 中（EnergyStoragePlanVo 对象）
              if (res.data) {
                if (res.data.entity) {
                  // 返回的完整数据对象，包含所有步骤的数据和规划结果
                  // 使用 $set 确保响应式更新
                  this.$set(this.formData, 'resultData', res.data.entity)
                } else if (typeof res.data === 'object' && !Array.isArray(res.data)) {
                  // 如果直接是对象，也保存
                  this.$set(this.formData, 'resultData', res.data)
                }
              }
              console.log('第四步返回数据:', res.data)
              console.log('保存的规划结果数据:', this.formData.resultData)
              console.log('suggestPlanCapacity:', this.formData.resultData?.suggestPlanCapacity)
              console.log('pcsRecommendValue:', this.formData.resultData?.pcsRecommendValue)
              console.log('expectedInvestReturnPeriod:', this.formData.resultData?.expectedInvestReturnPeriod)
              console.log('avgDayChargeDischargeTimes:', this.formData.resultData?.avgDayChargeDischargeTimes)
              this.$message.success('提交成功')
              // 进入下一步（查看规划结果）
              if (this.currentStep < this.steps.length - 1) {
                this.currentStep++
              }
            } else {
              this.$message.error(res.message || '提交失败')
            }
          } catch (error) {
            console.error('保存第四步数据失败:', error)
            this.$message.error('保存失败，请重试')
          }
        } else {
          // 如果没有 ref，直接进入下一步
          if (this.currentStep < this.steps.length - 1) {
            this.currentStep++
          }
        }
      } else {
        // 其他步骤直接进入下一步
        if (this.currentStep < this.steps.length - 1) {
          this.currentStep++
        }
      }
    },
    // 更新表单数据
    handleFormDataUpdate(data) {
      this.formData = { ...this.formData, ...data }
    },
    // 返回列表
    handleGoBack() {
      this.$emit('goback')
    },
    // 重置表单
    resetForm() {
      this.currentStep = 0
      this.formData = {
        region: '',
        projectName: '',
        priceSchemeId: '',
        month: '',
        priceConfig: {
          peak: { price: '0.00', timePeriods: [] },
          high: { price: '0.00', timePeriods: [] },
          flat: { price: '0.00', timePeriods: [] },
          offPeak: { price: '0.00', timePeriods: [] },
          superOffPeak: { price: '0.00', timePeriods: [] }
        },
        stepTwoData: {},
        stepThreeData: {},
        stepFourData: {}
      }
    },
    // 从初始数据加载（不调用接口，直接使用已获取的数据）
    async loadDataFromInitial(data, mode) {
      if (!data) {
        return
      }

      try {
        // 保存模式（view 或 edit）
        this.mode = mode
        // 保存规划ID
        this.formData.stepOneId = data.id

        // 第一步数据
        this.formData.region = data.region || ''
        this.formData.projectName = data.projectName || ''
        this.formData.priceSchemeId = data.electricPricePlanId || ''
        this.formData.month = data.electricPricePlanMonth || ''

        // 如果有电价方案JSON，需要加载到 PriceConfig 组件
        // 先等待 StepOne 组件加载电价方案列表，然后再设置 priceSchemeData
        if (data.electricPricePlanJson && data.electricPricePlanId) {
          // 等待 StepOne 组件加载电价方案列表
          await this.$nextTick()
          // 轮询等待电价方案列表加载完成
          const checkAndSetPriceConfig = () => {
            if (this.$refs.stepOne) {
              // 如果电价方案列表已加载
              if (this.$refs.stepOne.priceSchemeList && this.$refs.stepOne.priceSchemeList.length > 0) {
                // 找到对应的电价方案
                const priceScheme = this.$refs.stepOne.priceSchemeList.find(
                  (item) => item.id === data.electricPricePlanId
                )
                if (priceScheme && this.$refs.stepOne.$refs.priceConfig) {
                  // 设置 priceSchemeData，触发 PriceConfig 加载
                  this.$refs.stepOne.$refs.priceConfig.priceSchemeData = {
                    ...priceScheme,
                    priceJson: data.electricPricePlanJson
                  }
                  // 设置 selectedMonth
                  this.$refs.stepOne.$refs.priceConfig.selectedMonth = data.electricPricePlanMonth
                  return true
                } else if (this.$refs.stepOne.$refs.priceConfig) {
                  // 如果找不到方案，直接使用返回的 JSON 构造一个方案对象
                  this.$refs.stepOne.$refs.priceConfig.priceSchemeData = {
                    id: data.electricPricePlanId,
                    name: '',
                    priceJson: data.electricPricePlanJson
                  }
                  this.$refs.stepOne.$refs.priceConfig.selectedMonth = data.electricPricePlanMonth
                  return true
                }
              }
            }
            return false
          }

          // 立即尝试一次
          if (!checkAndSetPriceConfig()) {
            // 如果还没加载完成，轮询等待（最多等待2秒）
            let attempts = 0
            const maxAttempts = 20 // 20次 * 100ms = 2秒
            const interval = setInterval(() => {
              attempts++
              if (checkAndSetPriceConfig() || attempts >= maxAttempts) {
                clearInterval(interval)
              }
            }, 100)
          }
        }

        // 第二步数据
        this.formData.stepTwoData = {
          considerWeekendFlag: data.considerWeekendFlag !== undefined ? data.considerWeekendFlag : true,
          futureLoadGrowthRatio: data.futureLoadGrowthRatio || 100,
          fullChargeFullDischargeDay: data.fullChargeFullDischargeDay || 100,
          loadDetailsList: data.loadDetailsList || []
        }
        // 如果 StepTwo 组件已渲染，设置数据
        this.$nextTick(() => {
          if (this.$refs.stepTwo) {
            this.$refs.stepTwo.loadDetailsList = data.loadDetailsList || []
            this.$refs.stepTwo.form.considerWeekendFlag = data.considerWeekendFlag !== undefined ? data.considerWeekendFlag : true
            this.$refs.stepTwo.form.futureLoadGrowthRatio = data.futureLoadGrowthRatio || 100
            this.$refs.stepTwo.form.fullChargeFullDischargeDay = data.fullChargeFullDischargeDay || 100
          }
        })

        // 第三步数据
        this.formData.stepThreeData = {
          transformerCapacity: data.transformerCapacity || '',
          backflowPreventionFlag: data.backflowPreventionFlag !== undefined ? data.backflowPreventionFlag : false,
          antiOverloadFlag: data.antiOverloadFlag !== undefined ? data.antiOverloadFlag : false,
          chargeDischargeTimesType: data.chargeDischargeTimesType || 1,
          flatChargeFlag: data.flatChargeFlag !== undefined ? data.flatChargeFlag : false
        }
        // 如果 StepThree 组件已渲染，设置数据
        this.$nextTick(() => {
          if (this.$refs.stepThree) {
            this.$refs.stepThree.form.transformerCapacity = data.transformerCapacity || ''
            this.$refs.stepThree.form.backflowPreventionFlag = data.backflowPreventionFlag !== undefined ? data.backflowPreventionFlag : false
            this.$refs.stepThree.form.antiOverloadFlag = data.antiOverloadFlag !== undefined ? data.antiOverloadFlag : false
            this.$refs.stepThree.form.chargeDischargeTimesType = data.chargeDischargeTimesType || 1
            this.$refs.stepThree.form.flatChargeFlag = data.flatChargeFlag !== undefined ? data.flatChargeFlag : false
          }
        })

        // 第四步数据
        this.formData.stepFourData = {
          singleWattCost: data.singleWattCost || '',
          dischargeDepth: data.dischargeDepth || '',
          batteryEfficiency: data.batteryEfficiency || '',
          pcsEfficiency: data.pcsEfficiency || '',
          otherEfficiency: data.otherEfficiency || '',
          selfConsumptionElectricity: data.selfConsumptionElectricity || ''
        }
        // 如果 StepFour 组件已渲染，设置数据
        this.$nextTick(() => {
          if (this.$refs.stepFour) {
            this.$refs.stepFour.form.singleWattCost = data.singleWattCost || ''
            this.$refs.stepFour.form.dischargeDepth = data.dischargeDepth || ''
            this.$refs.stepFour.form.batteryEfficiency = data.batteryEfficiency || ''
            this.$refs.stepFour.form.pcsEfficiency = data.pcsEfficiency || ''
            this.$refs.stepFour.form.otherEfficiency = data.otherEfficiency || ''
            this.$refs.stepFour.form.selfConsumptionElectricity = data.selfConsumptionElectricity || ''
          }
        })

        // 规划结果数据
        if (data.suggestPlanCapacity || data.pcsRecommendValue || data.expectedInvestReturnPeriod || data.avgDayChargeDischargeTimes) {
          this.$set(this.formData, 'resultData', {
            suggestPlanCapacity: data.suggestPlanCapacity,
            pcsRecommendValue: data.pcsRecommendValue,
            expectedInvestReturnPeriod: data.expectedInvestReturnPeriod,
            avgDayChargeDischargeTimes: data.avgDayChargeDischargeTimes,
            electricPricePlanJson: data.electricPricePlanJson,
            electricPricePlanMonth: data.electricPricePlanMonth,
            loadDetailsList: data.loadDetailsList || []
          })
        }

        // 根据 stepNo 跳转到对应步骤（如果有）
        if (data.stepNo !== undefined && data.stepNo !== null) {
          // stepNo: 0-第一步, 1-第二步, 2-第三步, 3-第四步, 4-第五步（查看结果）
          this.currentStep = Math.min(data.stepNo, this.steps.length - 1)
        } else {
          // 如果没有 stepNo，根据是否有规划结果判断
          if (data.suggestPlanCapacity || data.pcsRecommendValue) {
            this.currentStep = 4 // 跳转到查看结果
          } else {
            this.currentStep = 0 // 默认第一步
          }
        }

        // 查看模式：禁用所有输入（通过设置只读属性）
        if (mode === 'view') {
          this.isViewMode = true
        } else {
          this.isViewMode = false
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请稍后重试')
      }
    },
    // 加载数据（编辑/查看模式）- 保留原有方法以兼容
    async loadData(id, mode) {
      try {
        const res = await getEnergyStoragePlanByIdApi({ id: id.toString() })
        if (res && res.code === 200 && res.data) {
          const data = res.data.entity || res.data
          if (!data) {
            this.$message.error('获取数据失败')
            return
          }

          // 保存模式（view 或 edit）
          this.mode = mode
          // 保存规划ID
          this.formData.stepOneId = data.id

          // 第一步数据
          this.formData.region = data.region || ''
          this.formData.projectName = data.projectName || ''
          this.formData.priceSchemeId = data.electricPricePlanId || ''
          this.formData.month = data.electricPricePlanMonth || ''

          // 如果有电价方案JSON，需要加载到 PriceConfig 组件
          // 先等待 StepOne 组件加载电价方案列表，然后再设置 priceSchemeData
          if (data.electricPricePlanJson && data.electricPricePlanId) {
            // 等待 StepOne 组件加载电价方案列表
            await this.$nextTick()
            // 等待一下，让 StepOne 有时间加载电价方案列表
            setTimeout(() => {
              if (this.$refs.stepOne) {
                // 找到对应的电价方案
                const priceScheme = this.$refs.stepOne.priceSchemeList?.find(
                  (item) => item.id === data.electricPricePlanId
                )
                if (priceScheme && this.$refs.stepOne.$refs.priceConfig) {
                  // 设置 priceSchemeData，触发 PriceConfig 加载
                  this.$refs.stepOne.$refs.priceConfig.priceSchemeData = {
                    ...priceScheme,
                    priceJson: data.electricPricePlanJson
                  }
                  // 设置 selectedMonth
                  this.$refs.stepOne.$refs.priceConfig.selectedMonth = data.electricPricePlanMonth
                } else if (this.$refs.stepOne.$refs.priceConfig) {
                  // 如果找不到方案，直接使用返回的 JSON 构造一个方案对象
                  this.$refs.stepOne.$refs.priceConfig.priceSchemeData = {
                    id: data.electricPricePlanId,
                    name: '',
                    priceJson: data.electricPricePlanJson
                  }
                  this.$refs.stepOne.$refs.priceConfig.selectedMonth = data.electricPricePlanMonth
                }
              }
            }, 500) // 等待 500ms，确保电价方案列表已加载
          }

          // 第二步数据
          this.formData.stepTwoData = {
            considerWeekendFlag: data.considerWeekendFlag !== undefined ? data.considerWeekendFlag : true,
            futureLoadGrowthRatio: data.futureLoadGrowthRatio || 100,
            fullChargeFullDischargeDay: data.fullChargeFullDischargeDay || 100,
            loadDetailsList: data.loadDetailsList || []
          }
          // 如果 StepTwo 组件已渲染，设置数据
          this.$nextTick(() => {
            if (this.$refs.stepTwo) {
              this.$refs.stepTwo.loadDetailsList = data.loadDetailsList || []
              this.$refs.stepTwo.form.considerWeekendFlag = data.considerWeekendFlag !== undefined ? data.considerWeekendFlag : true
              this.$refs.stepTwo.form.futureLoadGrowthRatio = data.futureLoadGrowthRatio || 100
              this.$refs.stepTwo.form.fullChargeFullDischargeDay = data.fullChargeFullDischargeDay || 100
            }
          })

          // 第三步数据
          this.formData.stepThreeData = {
            transformerCapacity: data.transformerCapacity || '',
            backflowPreventionFlag: data.backflowPreventionFlag !== undefined ? data.backflowPreventionFlag : false,
            antiOverloadFlag: data.antiOverloadFlag !== undefined ? data.antiOverloadFlag : false,
            chargeDischargeTimesType: data.chargeDischargeTimesType || 1,
            flatChargeFlag: data.flatChargeFlag !== undefined ? data.flatChargeFlag : false
          }
          // 如果 StepThree 组件已渲染，设置数据
          this.$nextTick(() => {
            if (this.$refs.stepThree) {
              this.$refs.stepThree.form.transformerCapacity = data.transformerCapacity || ''
              this.$refs.stepThree.form.backflowPreventionFlag = data.backflowPreventionFlag !== undefined ? data.backflowPreventionFlag : false
              this.$refs.stepThree.form.antiOverloadFlag = data.antiOverloadFlag !== undefined ? data.antiOverloadFlag : false
              this.$refs.stepThree.form.chargeDischargeTimesType = data.chargeDischargeTimesType || 1
              this.$refs.stepThree.form.flatChargeFlag = data.flatChargeFlag !== undefined ? data.flatChargeFlag : false
            }
          })

          // 第四步数据
          this.formData.stepFourData = {
            singleWattCost: data.singleWattCost || '',
            dischargeDepth: data.dischargeDepth || '',
            batteryEfficiency: data.batteryEfficiency || '',
            pcsEfficiency: data.pcsEfficiency || '',
            otherEfficiency: data.otherEfficiency || '',
            selfConsumptionElectricity: data.selfConsumptionElectricity || ''
          }
          // 如果 StepFour 组件已渲染，设置数据
          this.$nextTick(() => {
            if (this.$refs.stepFour) {
              this.$refs.stepFour.form.singleWattCost = data.singleWattCost || ''
              this.$refs.stepFour.form.dischargeDepth = data.dischargeDepth || ''
              this.$refs.stepFour.form.batteryEfficiency = data.batteryEfficiency || ''
              this.$refs.stepFour.form.pcsEfficiency = data.pcsEfficiency || ''
              this.$refs.stepFour.form.otherEfficiency = data.otherEfficiency || ''
              this.$refs.stepFour.form.selfConsumptionElectricity = data.selfConsumptionElectricity || ''
            }
          })

          // 规划结果数据
          if (data.suggestPlanCapacity || data.pcsRecommendValue || data.expectedInvestReturnPeriod || data.avgDayChargeDischargeTimes) {
            this.$set(this.formData, 'resultData', {
              suggestPlanCapacity: data.suggestPlanCapacity,
              pcsRecommendValue: data.pcsRecommendValue,
              expectedInvestReturnPeriod: data.expectedInvestReturnPeriod,
              avgDayChargeDischargeTimes: data.avgDayChargeDischargeTimes,
              electricPricePlanJson: data.electricPricePlanJson,
              electricPricePlanMonth: data.electricPricePlanMonth,
              loadDetailsList: data.loadDetailsList || []
            })
          }

          // 根据 stepNo 跳转到对应步骤（如果有）
          if (data.stepNo !== undefined && data.stepNo !== null) {
            // stepNo: 0-第一步, 1-第二步, 2-第三步, 3-第四步, 4-第五步（查看结果）
            this.currentStep = Math.min(data.stepNo, this.steps.length - 1)
          } else {
            // 如果没有 stepNo，根据是否有规划结果判断
            if (data.suggestPlanCapacity || data.pcsRecommendValue) {
              this.currentStep = 4 // 跳转到查看结果
            } else {
              this.currentStep = 0 // 默认第一步
            }
          }

          // 查看模式：禁用所有输入（通过设置只读属性）
          if (mode === 'view') {
            this.isViewMode = true
          } else {
            this.isViewMode = false
          }
        } else {
          this.$message.error(res.message || '获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请稍后重试')
      }
    },
    // 完成
    async handleComplete() {
      try {
        // 第五步：保存规划结果数据
        if (!this.formData.resultData) {
          this.$message.warning('请先完成规划分析')
          return
        }

        const submitData = {
          id: this.formData.stepOneId ? Number(this.formData.stepOneId) : null,
          suggestPlanCapacity: this.formData.resultData.suggestPlanCapacity
            ? Number(this.formData.resultData.suggestPlanCapacity)
            : null,
          pcsRecommendValue: this.formData.resultData.pcsRecommendValue || '',
          expectedInvestReturnPeriod: this.formData.resultData.expectedInvestReturnPeriod
            ? Number(this.formData.resultData.expectedInvestReturnPeriod)
            : null,
          avgDayChargeDischargeTimes: this.formData.resultData.avgDayChargeDischargeTimes
            ? Number(this.formData.resultData.avgDayChargeDischargeTimes)
            : null
        }

        const res = await stepFiveAddOrUpdateApi(submitData)
        if (res && res.code === 200) {
          this.$message.success('保存成功')
          this.handleGoBack()
        } else {
          this.$message.error(res.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败，请重试')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.energy-storage-planning-box {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  background-color: #f1f1f1;
  height: 100vh;
  width: 100vw;
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  overflow: auto;

  .form-header {
    background-color: #fff;
    padding: 15px 20px;
    border-radius: 0;
  }

  .step-navigation {
    padding: 20px 300px;
    background-color: #fff;
    border-radius: 0;
  }

  .step-content {
    flex: 1;
    background-color: #fff;
    padding: 20px 300px;
    border-radius: 0;
    overflow: auto;
  }

  .footer-actions {
    text-align: right;
    padding: 20px 300px;
    background-color: #fff;
    border-radius: 0;

    .el-button {
      margin-left: 10px;
    }
  }
}
</style>
